package com.flyco.modules.cms.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.flyco.common.util.DateUtils;
import com.flyco.modules.cms.vo.CmsImageTagProductPage;
import com.flyco.modules.cms.vo.CmsImageTagProductVO;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.cms.entity.CmsImageTagProduct;
import com.flyco.modules.cms.entity.CmsImageTag;
import com.flyco.modules.cms.vo.CmsImageTagPage;
import com.flyco.modules.cms.service.ICmsImageTagService;
import com.flyco.modules.cms.service.ICmsImageTagProductService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

 /**
 * @Description: 活动图标管理
 * @Author: flyco
 * @Date:   2019-12-25
 * @Version: V1.0
 */
@RestController
@RequestMapping("/f/cms/cmsImageTag")
@Slf4j
public class CmsImageTagController {
	@Autowired
	private ICmsImageTagService cmsImageTagService;
	@Autowired
	private ICmsImageTagProductService cmsImageTagProductService;
	
	/**
	 * 分页列表查询
	 *
	 * @param cmsImageTag
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(CmsImageTag cmsImageTag,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<CmsImageTag> queryWrapper = QueryGenerator.initQueryWrapper(cmsImageTag, req.getParameterMap());
		Page<CmsImageTag> page = new Page<CmsImageTag>(pageNo, pageSize);
		IPage<CmsImageTag> pageList = cmsImageTagService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param cmsImageTagPage
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody CmsImageTagPage cmsImageTagPage) {
       	CmsImageTag cmsImageTag = new CmsImageTag();
		BeanUtils.copyProperties(cmsImageTagPage, cmsImageTag);
		if(null != cmsImageTag.getEndTime()) {
			cmsImageTag.setEndTime(DateUtils.endOfDay(cmsImageTag.getEndTime()));
		}
		cmsImageTag.setCancelFlag(0);
		cmsImageTagService.save(cmsImageTag);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cmsImageTagPage
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody CmsImageTagPage cmsImageTagPage) {
		CmsImageTag cmsImageTag = new CmsImageTag();
		BeanUtils.copyProperties(cmsImageTagPage, cmsImageTag);
		if(null != cmsImageTag.getEndTime()) {
			cmsImageTag.setEndTime(DateUtils.endOfDay(cmsImageTag.getEndTime()));
		}
		cmsImageTagService.updateById(cmsImageTag);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		cmsImageTagService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	    this.cmsImageTagService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		CmsImageTag cmsImageTag = cmsImageTagService.getById(id);
		return Result.ok(cmsImageTag);
	}
	
	//===========================以下是子表信息操作相关API====================================
	
	/**
	 * 通过主表id查询关联商品
	 *
  	 * @param cmsImageTagProduct
	 * @return
	 */
	@GetMapping(value = "/listCmsImageTagProductByMainId")
	public Result<?> listCmsImageTagProductByMainId(CmsImageTagProductPage cmsImageTagProduct,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(cmsImageTagProduct.getImageTagId()!=null) {
            QueryWrapper<CmsImageTagProductPage> queryWrapper = QueryGenerator.initQueryWrapper(cmsImageTagProduct, req.getParameterMap());
            Page<CmsImageTagProductPage> page = new Page<CmsImageTagProductPage>(pageNo, pageSize);
            IPage<CmsImageTagProductPage> pageList =  cmsImageTagProductService.getImageTagProductPage(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.error("没有选择记录");
        }
    }
	
	/**
     * 添加商品关联
     *
     * @param vo
     * @return
     */
    @PostMapping(value = "/addCmsImageTagProduct")
    public Result<?> addCmsImageTagProduct(@RequestBody CmsImageTagProductVO vo) {
		if(null != vo && null != vo.getProductIdList() && null != vo.getImageTagId()) {
			List<CmsImageTagProduct> cmsImageTagProductList = cmsImageTagProductService.selectByMainId(vo.getImageTagId());
			List<Long> dbList = cmsImageTagProductList.stream().map(CmsImageTagProduct::getProductId).collect(Collectors.toList());
			vo.getProductIdList().removeAll(dbList);
			List<CmsImageTagProduct> tagProducts = new ArrayList<>();
			for (Long productId : vo.getProductIdList()){
				CmsImageTagProduct tagProduct = new CmsImageTagProduct();
				tagProduct.setImageTagId(vo.getImageTagId());
				tagProduct.setProductId(productId);
				tagProducts.add(tagProduct);
			}
			cmsImageTagProductService.saveBatch(tagProducts);
			return Result.ok("添加商品关联成功！");
		}
        return Result.error("添加商品关联失败！");
    }
    
    /**
     * 编辑商品关联
     *
     * @param cmsImageTagProduct
     * @return
     */
    @PutMapping("/editCmsImageTagProduct")
    public Result<?> editCmsImageTagProduct(@RequestBody CmsImageTagProduct cmsImageTagProduct) {
        cmsImageTagProductService.updateById(cmsImageTagProduct);
        return Result.ok("编辑商品关联成功！");
    }
    
    /**
     * 通过id删除商品关联
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deleteCmsImageTagProduct")
    public Result<?> deleteCmsImageTagProduct(@RequestParam(name = "id", required = true) String id) {
       cmsImageTagProductService.removeById(id);
        return Result.ok("删除商品关联成功！");
    }
	
	/**
     * 批量删除商品关联
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchCmsImageTagProduct")
    public Result<?> deleteBatchCmsImageTagProduct(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.cmsImageTagProductService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }
    

    /**
    * 导出excel
    *
    * @param request
    * @param cmsImageTag
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CmsImageTag cmsImageTag) {
      // Step.1 组装查询条件
      QueryWrapper<CmsImageTag> queryWrapper = QueryGenerator.initQueryWrapper(cmsImageTag, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<CmsImageTagPage> pageList = new ArrayList<CmsImageTagPage>();
      List<CmsImageTag> cmsImageTagList = cmsImageTagService.list(queryWrapper);
      for (CmsImageTag temp : cmsImageTagList) {
          CmsImageTagPage vo = new CmsImageTagPage();
          BeanUtils.copyProperties(temp, vo);
          List<CmsImageTagProduct> cmsImageTagProductList = cmsImageTagProductService.selectByMainId(temp.getId());
          vo.setCmsImageTagProductList(cmsImageTagProductList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "活动图标管理");
      mv.addObject(NormalExcelConstants.CLASS, CmsImageTagPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("活动图标管理数据", "导出人:"+sysUser.getRealname(), "活动图标管理"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<CmsImageTagPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CmsImageTagPage.class, params);
              for (CmsImageTagPage page : list) {
                  CmsImageTag po = new CmsImageTag();
                  BeanUtils.copyProperties(page, po);
                  cmsImageTagService.saveMain(po, page.getCmsImageTagProductList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
}
